package com.xz.sanitize.serializer;

import com.xz.sanitize.strategy.DefaultValueProvider;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.BeanPropertyWriter;

import java.io.IOException;

/**
 * 当遇到空值时写入默认值（包括嵌套的bean对象）。
 */
class DefaultingPropertyWriter extends BeanPropertyWriter {
    private final BeanPropertyWriter delegate;
    private final DefaultValueProvider provider;

    DefaultingPropertyWriter(BeanPropertyWriter delegate, DefaultValueProvider provider) {
        super(delegate);
        this.delegate = delegate;
        this.provider = provider;
    }

    @Override
    public void serializeAsField(Object bean, JsonGenerator gen, SerializerProvider prov) throws Exception {
        Object value = delegate.get(bean);
        if (value == null) {
            JavaType type = prov.constructType(delegate.getType());
            Object def = provider.defaultFor(type);
            if (def == null) {
                super.serializeAsField(bean, gen, prov);
                return;
            }
            writeValue(gen, prov, def);
            return;
        }
        delegate.serializeAsField(bean, gen, prov);
    }

    private void writeValue(JsonGenerator gen, SerializerProvider prov, Object def) throws IOException {
        if (def == null) {
            gen.writeNull();
        } else {
            gen.writeFieldName(getName());
            JsonSerializer<Object> ser = prov.findValueSerializer(def.getClass());
            ser.serialize(def, gen, prov);
        }
    }
}
